from google.appengine.ext import webapp
from django.utils import simplejson
import time, datetime
import pprint

from voteDb import voteDB

class AdminDebates(webapp.RequestHandler):
  def get(self):
    timfrmt = "%Y-%m-%d %H:%M:%S"
    userid = self.request.get("userid")
    debates = voteDB.DebateIndex()
    rtv = []
    for deb in debates:
      rtv.append({
        'debate_key': str(deb.key()),
        'creator': deb.creator,
        'createtime': deb.createtime.strftime(timfrmt),
        'lasteditor': deb.lasteditor,
        'lastedittime': deb.lastedittime.strftime(timfrmt),
        'summary': deb.summary,
        'motion': deb.motion,
        'proposition': deb.proposition,
        'opposition': deb.opposition,
        'starttime': deb.starttime.strftime(timfrmt),
        'endtime': deb.endtime.strftime(timfrmt),
        'voteendtime': deb.voteendtime.strftime(timfrmt),
        'timeremaining': int(time.mktime(deb.endtime.timetuple())) - int(time.mktime(datetime.datetime.now().timetuple())),
        'timeremainingvote': int(time.mktime(deb.voteendtime.timetuple())) - int(time.mktime(datetime.datetime.now().timetuple())),
        'votesfor': deb.forit,
        'votesagainst': deb.againstit
      })
    rtvmeta = {
      'title': "Debatewise - Copenhagen Debates, 2009",
      'summary': "A summary",
      'startdate': "2009-12-07 12:00:00 UTC",
      'creator': "davidcrane@googlewave.com",
      'debates': rtv
    }
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtvmeta))


class AdminDebateAdd(webapp.RequestHandler):
  def get(self):
    userid = self.request.get("userid")
    admin = voteDB.AdminCheck(userid)
    admin = "asdf"
    if admin != None:
      try:
        timfrmt = "%Y-%m-%d %H:%M:%S"
        motion = self.request.get("motion")
        summary = self.request.get("summary")
        proposition = self.request.get("proposition")
        opposition = self.request.get("opposition")
        starttime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self.request.get("starttime"), timfrmt)))
        endtime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self.request.get("endtime"), timfrmt)))
        voteendtime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self.request.get("voteendtime"), timfrmt)))
        if len(motion) > 0:
          debate_key = voteDB.DebateAdd(motion, summary, proposition, opposition, starttime, endtime, voteendtime, userid)
          rv = str(debate_key)
        else:
          rv = 0
        rtv = {'success': rv}
      except ValueError:
        rtv = {'error': "Invalid data"}
      #except:
      #  rtv = {'error': "Error"}
    else:
      rtv = {'error': "Not authorisied"}
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtv))

class AdminIndexes(webapp.RequestHandler):
  def get(self):
    userid = self.request.get("userid")
    admin = voteDB.AdminCheck(userid)
    if admin != None:
      indexes = voteDB.DebateIndexes()
      rtv = []
      for i in indexes:
        rtv.append({
          'name': i.name,
          'waveid': i.waveid,
          'creator': i.creator,
          'participants': voteDB.DebateParticipants(i.key())
        })
    else:
      rtv = {'error': "Not authorisied"}
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtv))

class AdminIndexAdd(webapp.RequestHandler):
  def get(self):
    userid = self.request.get("userid")
    admin = voteDB.AdminCheck(userid)
    if admin != None:
      name = self.request.get("name")
      waveid = self.request.get("waveid")
      creator = self.request.get("creator")
      rtv = {'success': str(voteDB.DebateIndexAdd(waveid, name, creator))}
    else:
      rtv = {'error': "Not authorisied"}
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtv))

class AdminIndexParticipantAdd(webapp.RequestHandler):
  def get(self):
    userid = self.request.get("userid")
    admin = voteDB.AdminCheck(userid)
    if admin != None:
      waveid = self.request.get("waveid")
      participant = self.request.get("participant")
      name = self.request.get("name")
      rtv = {'success': str(voteDB.DebateIndexAddParticipant(waveid, participant, name))}
    else:
      rtv = {'error': "Not authorisied"}
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtv))

class UserIndex(webapp.RequestHandler):
  def get(self):
    timfrmt = "%Y-%m-%d %H:%M:%S"
    userid = self.request.get("userid")
    debates = voteDB.DebateIndex()
    rtv = []
    for deb in debates:
      exists = voteDB.UsersDebateGet(userid, deb.key())
      if exists != None:
        waveid = exists.waveid
      else:
        waveid = ''
      rtv.append({
        'debate_key': str(deb.key()),
        'creator': deb.creator,
        'createtime': deb.createtime.strftime(timfrmt),
        'lasteditor': deb.lasteditor,
        'lastedittime': deb.lastedittime.strftime(timfrmt),
        'summary': deb.summary,
        'motion': deb.motion,
        'proposition': deb.proposition,
        'opposition': deb.opposition,
        'starttime': deb.starttime.strftime(timfrmt),
        'endtime': deb.endtime.strftime(timfrmt),
        'voteendtime': deb.voteendtime.strftime(timfrmt),
        'timeremaining': int(time.mktime(deb.endtime.timetuple())) - int(time.mktime(datetime.datetime.now().timetuple())),
        'timeremainingvote': int(time.mktime(deb.voteendtime.timetuple())) - int(time.mktime(datetime.datetime.now().timetuple())),
        'votesfor': deb.forit,
        'votesagainst': deb.againstit,
        'waveid': waveid
      })
    ## Todo -- Add this to a Meta Table.
    rtvmeta = {
      'title': "Debatewise - Copenhagen Debates, 2009",
      'summary': "A summary",
      'startdate': "2009-12-07 12:00:00 UTC",
      'creator': "davidcrane@googlewave.com",
      'debates': rtv
    }
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtvmeta))

class DebateGet(webapp.RequestHandler):
  def get(self):
    timfrmt = "%Y-%m-%d %H:%M:%S"
    debate_key = self.request.get("debate_key")
    userid = self.request.get("userid")
    if len(debate_key) > 0:
      deb = voteDB.GetRawKey(debate_key)
      if deb != None:
        points = voteDB.DebatePointsGet(deb.key())
        pnts = []
        if points != None:
          for p in points:
            pnts.append({
              'creator': p.creator,
              'createtime': p.createtime.strftime(timfrmt),
              'lasteditor': p.lasteditor,
              'lastedittime': p.lastedittime.strftime(timfrmt),
              'pointtitle': p.pointtitle,
              'point': p.point,
              'counterpointtitle': p.counterpointtitle,
              'counterpoint': p.counterpoint,
              'foragainst': p.foragainst,
              'rating': p.rating,
              'waveid': p.waveid
            })
        debvotes = voteDB.DebateVotesGet(debate_key, userid)
        rtv = {
          'debate_key': str(deb.key()),
          'creator': deb.creator,
          'createtime': deb.createtime.strftime(timfrmt),
          'lasteditor': deb.lasteditor,
          'lastedittime': deb.lastedittime.strftime(timfrmt),
          'summary': deb.summary,
          'motion': deb.motion,
          'proposition': deb.proposition,
          'opposition': deb.opposition,
          'starttime': deb.starttime.strftime(timfrmt),
          'endtime': deb.endtime.strftime(timfrmt),
          'voteendtime': deb.voteendtime.strftime(timfrmt),
          'timeremaining': int(time.mktime(deb.endtime.timetuple())) - int(time.mktime(datetime.datetime.now().timetuple())),
          'timeremainingvote': int(time.mktime(deb.voteendtime.timetuple())) - int(time.mktime(datetime.datetime.now().timetuple())),
          'votesfor': debvotes['forit'],
          'votesagainst': debvotes['againstit'],
          'yourvote': debvotes['yourvote'],
          'points': pnts
        }

      else:
        rtv = {}
    else:
      rtv = {}
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtv))

class DebateEdit(webapp.RequestHandler):
  def get(self):
    try:
      timfrmt = "%Y-%m-%d %H:%M:%S"
      debate_key = self.request.get("debate_key")
      motion = self.request.get("motion")
      summary = self.request.get("summary")
      proposition = self.request.get("proposition")
      opposition = self.request.get("opposition")
      userid = self.request.get("userid")
      rv = voteDB.DebateEdit(debate_key, motion, summary, proposition, opposition, userid)
      if len(str(rv)) > 1:
        rtv = {'success': str(rv)}
      else:
        rtv = {'error': "Failed to update"}
    except ValueError:
      rtv = {'error': "Invalid data"}
    except:
      rtv = {'error': "Error"}
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtv))

class DebateVotesGet(webapp.RequestHandler):
  def get(self):
    debate_key = self.request.get("debate_key")
    userid = self.request.get("userid")
    rtv = voteDB.DebateVotesGet(debate_key, userid)
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtv))

class DebateVotes(webapp.RequestHandler):
  def get(self):
    timfrmt = "%Y-%m-%d %H:%M:%S"
    debate_key = self.request.get("debate_key")
    vots = voteDB.DebateVotes(debate_key)
    rtv = ""
    for v in vots:
      rtv += "</br> " + str(v.debate) + " : " + v.userid + " : " + v.timestamp.strftime(timfrmt) + " - " + str(v.foragainst)
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(rtv)

class DebateVote(webapp.RequestHandler):
  def get(self):
    debate_key = self.request.get("debate_key")
    userid = self.request.get("userid")
    foragainst = self.request.get("foragainst")
    rv = voteDB.DebateVote(debate_key, userid, foragainst)
    rtv = voteDB.DebateVotesGet(debate_key, userid)
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtv))

class DebateRollback(webapp.RequestHandler):
  def get(self):
    debate_key = self.request.get("debate_key")
    userid = self.request.get("userid")
    rtv = voteDB.DebateRollback(debate_key)
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(str(rtv))) # TODO better rtv

class PointGet(webapp.RequestHandler):
  def get(self):
    timfrmt = "%Y-%m-%d %H:%M:%S"
    waveid = self.request.get("waveid")
    userid = self.request.get("userid")
    point = voteDB.PointGet(waveid)
    rtv = {}
    if point != None:
      debate = point.debate
      if debate != None:
        rtv = {
          'debate_key': str(debate.key()),
          'motion': debate.motion,
          'waveid': waveid,
          'creator': point.creator,
          'created': point.createtime.strftime(timfrmt),
          'lasteditor': point.lasteditor,
          'lastedit': point.lastedittime.strftime(timfrmt),
          'pointtitle': point.pointtitle,
          'point': point.point,
          'counterpointtitle': point.counterpointtitle,
          'counterpoint': point.counterpoint,
          'foragainst': point.foragainst,
          'rating': point.rating,
          'yourrating': voteDB.PointUserRateGet(point.key(), userid),
          'starttiime': debate.starttime.strftime(timfrmt),
          'endtime': debate.endtime.strftime(timfrmt),
          'voteendtime': debate.voteendtime.strftime(timfrmt),
          'timeremaining': int(time.mktime(debate.endtime.timetuple())) - int(time.mktime(datetime.datetime.now().timetuple())),
          'timeremainingvote': int(time.mktime(debate.voteendtime.timetuple())) - int(time.mktime(datetime.datetime.now().timetuple())),
        }
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtv))

class PointAdd(webapp.RequestHandler):
  def get(self):
    debate_key = self.request.get("debate_key")
    waveid = self.request.get("waveid")
    userid = self.request.get("userid")
    pointtitle = self.request.get("pointtitle")
    point = self.request.get("point")
    foragainst = self.request.get("foragainst")
    rtv = voteDB.PointAdd(debate_key, waveid, point, pointtitle, foragainst, userid)
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(str(rtv))) ## TODO - Better rtv

class PointEdit(webapp.RequestHandler):
  def get(self):
    waveid = self.request.get("waveid")
    pnt = voteDB.PointGet(waveid)
    userid = self.request.get("userid")
    pointtitle = self.request.get("pointtitle")
    point = self.request.get("point")
    counterpointtitle = self.request.get("counterpointtitle")
    counterpoint = self.request.get("counterpoint")
    if len(point) > 0 and len(pointtitle) > 0:
      p = point
      pt = pointtitle
    else:
      p = pnt.point
      pt = pnt.pointtitle
    if len(counterpoint) > 0 and len(counterpointtitle) > 0:
      cp = counterpoint
      cpt = counterpointtitle
    else:
      cp = pnt.counterpoint
      cpt = pnt.counterpointtitle
    rtv = voteDB.PointEdit(pnt.key(), p, pt, cp, cpt, userid, pnt.foragainst)
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(str(rtv))) ## TODO - Better rtv

class PointRollback(webapp.RequestHandler):
  def get(self):
    waveid = self.request.get("waveid")
    pnt = voteDB.PointGet(waveid)
    userid = self.request.get("userid")
    rtv = voteDB.PointRollback(str(pnt.key()))
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(str(rtv)))

class PointRate(webapp.RequestHandler):
  def get(self):
    waveid = self.request.get("waveid")
    pnt = voteDB.PointGet(waveid)
    userid = self.request.get("userid")
    rate = self.request.get("rate")
    rtv = voteDB.PointRate(pnt.key(), userid, rate)
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(str(rtv))) ## TODO - Better rtv

def escape_quotes(st):
  return st.replace('"', '\\"')

class ExportDebates(webapp.RequestHandler):
  def get(self):
    debs = voteDB.DebateIndex()
    rtv = '"debate_key","motion","summary"' + "\n"
    for d in debs:
      rtv += '"' + str(d.key()) + '","' + escape_quotes(d.motion) + '","' + escape_quotes(d.summary) + '"' + "\n"
    self.response.headers['Content-Type'] = "text/plain"
    self.response.out.write(rtv)

class ExportPoints(webapp.RequestHandler):
  def get(self):
    pnts = voteDB.Points()
    rtv = '"debate_key","point_waveid","for_against","point","pointtitle","counterpoint","counterpointtitle","creator","lasteditor"' + "\n"
    for p in pnts:
      rtv += '"' + str(p.debate.key()) + '","' + p.waveid + '","' + str(p.foragainst) + '","' + p.point + '","' + p.pointtitle + '","' + p.counterpoint + '","' + p.counterpointtitle + '","' + p.creator + '","' + p.lasteditor + '"' + "\n"
    self.response.headers['Content-Type'] = "text/plain"
    self.response.out.write(rtv)

class ExportParticipants(webapp.RequestHandler):
  def get(self):
    peeps = voteDB.Participants()
    rtv = '"uid","userid","name","email","country"' + "\n"
    for p in peeps:
      rtv += '"' + p.uid + '","' + p.userid + '","' + p.name + '","' + p.email + '","' + p.country + '"' + "\n"
    self.response.headers['Content-Type'] = "text/plain"
    self.response.out.write(rtv)

class BlipRate(webapp.RequestHandler):
  def get(self):
    waveid = self.request.get("waveid")
    pnt = voteDB.PointGet(waveid)
    blipid = self.request.get("blipid")
    creator = self.request.get("creatorid")
    viewer = self.request.get("viewerid")
    like = self.request.get("like")
    rtv = voteDB.BlipRate(waveid, pnt, blipid, creator, viewer, like)
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(str(rtv))) ## TODO - Better rtv

class ExchangeAdd(webapp.RequestHandler):
  def get(self):
    key = self.request.get("key")
    waveid = self.request.get("waveid")
    userid = self.request.get("userid")
    rtv = voteDB.ExchangeAdd(key, waveid, userid)
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(str(rtv))) ## TODO - Better rtv

class ExchangeGet(webapp.RequestHandler):
  def get(self):
    key = self.request.get("key")
    waveid = self.request.get("waveid")
    userid = self.request.get("userid")
    if len(key) > 0:
      rtv = voteDB.ExchangeGet('keys', key)
    elif len(waveid) > 0:
      rtv = voteDB.ExchangeGet('waveid', waveid)
    elif len(userid) > 0:
      rtv = voteDB.ExchangeGet('userid', userid)
    else:
      rtv = {'error': "Invalid data"}
    ## self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(simplejson.dumps(rtv))

class DebDump(webapp.RequestHandler):
  def get(self):
    dat = voteDB.Participants()
    rtv = ""
    for d in dat:
      for c in d:
        rtv += str(c)
      rtv += "\n"
    self.response.headers['Content-Type'] = "text/plain"
    self.response.out.write(rtv)


